package com.wsd.smartcarwasher.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.*;
import java.net.URLDecoder;


public class PostImgUpload {

    public static String postImgUpload(String filePath) throws ClientProtocolException, IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("http://file.snail-tech.cn/mwxc/upload");// 请求地址
        MultipartEntityBuilder meb = MultipartEntityBuilder.create();
        meb.addBinaryBody("file", new File(filePath));// 文件路径
        HttpEntity httpEntity = meb.build();
        httpPost.setEntity(httpEntity);
        try {
            StringBuilder sb = new StringBuilder();
            String line;
            HttpResponse httpResponse = httpClient.execute(httpPost);
            InputStream inputStream = httpResponse.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String rspMsg = URLDecoder.decode(sb.toString(),"UTF-8");
            JSONObject response= JSONUtil.parseObj(rspMsg);
            if(response.getInt("code")==200)
            {
                JSONObject jsonObject=response.getJSONObject("data");
                return "http://file.snail-tech.cn/"+jsonObject.getStr("file_path");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
